package com.tanhua.api.mongo;

import com.tanhua.mongo.UserLike;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class UserLikeApiImpl implements UserLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Integer findLoveCount(Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        Long count = mongoTemplate.count(query, UserLike.class);
        return count.intValue();
    }

    @Override
    public Integer findFanCount(Long id) {
        Query query = new Query(Criteria.where("likeUserId").is(id));
        Long count = mongoTemplate.count(query, UserLike.class);
        return count.intValue();
    }

    @Override
    public PageBeanVo findLoveList(Integer page, Integer pagesize, Long id) {

        Query query = new Query(Criteria.where("userId").is(id));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<UserLike> list = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);
        return new PageBeanVo(page,pagesize,count,list);
    }

    @Override
    public PageBeanVo findFanList(Integer page, Integer pagesize, Long id) {
        Query query = new Query(Criteria.where("likeUserId").is(id));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<UserLike> list = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);
        return new PageBeanVo(page,pagesize,count,list);
    }

    @Override
    public void removeFans(Integer fanId, Long id) {
        Query query = new Query(Criteria.where("userId").is(fanId).and("likeUserId").is(id));
        mongoTemplate.remove(query,UserLike.class);
    }

    @Override
    public void addFans(Long userId, Integer loveId) {
        UserLike userLike = new UserLike();
        userLike.setUserId(loveId.longValue());
        userLike.setLikeUserId(userId);
        userLike.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(userLike);
    }
}
